package com.xwj.client;

import com.xwj.dto.ProviderInfo;
import com.xwj.dto.RpcRequest;
import com.xwj.server.ServiceDiscovery;

import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * @author xwj
 * @date 2020/7/21
 */
public class RpcProxy {
    private ServiceDiscovery serviceDiscovery;

    public ServiceDiscovery getServiceDiscovery() {
        return serviceDiscovery;
    }

    public void setServiceDiscovery(ServiceDiscovery serviceDiscovery) {
        this.serviceDiscovery = serviceDiscovery;
    }

    public <T> T create(Class<?> interfaceClass, String providerName) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass},
                (proxy, method, args) -> {
                    // 通过netty向Rpc服务发送请求
                    // 构建一个请求
                    RpcRequest request = new RpcRequest();
                    request.setRequestId(UUID.randomUUID().toString())
                            .setClassName(method.getDeclaringClass().getName())
                            .setMethodName(method.getName())
                            .setParamTypes(method.getParameterTypes())
                            .setParams(args);
                    // 获取一个服务提供者
                    ProviderInfo providerInfo = serviceDiscovery.discover(providerName);
                    // 解析服务提供者的地址信息，数组第一个元素为ip地址，第二个元素为端口号
                    String[] addrInfo = providerInfo.getAddr().split(":");
                    String host = addrInfo[0];
                    int port = Integer.parseInt(addrInfo[1]);
                    return null;
                });
    }
}
